function [grid,xnew,znew]=gridmarkers(mscalar,mx,mz,mcs,mct,x,z,Snew,Tnew)
mx=mx'; mz=mz'; mscalar=mscalar';

s=mcs'; t=mct';
N=length(mscalar); S=length(x); T=length(z);
dx=diff(x); dz=diff(z);

grid=zeros(S,T); weight=zeros(S,T);
INV=t*S+s+1;
INE=t*S+s+2;
ISV=(t+1)*S+s+1;
ISE=(t+1)*S+s+2;
s=s+1; t=t+1;
dlx=(mx-x(s))./dx(s);
dlz=(mz-z(t))./dz(t);
% NV
dw=(1-dlx).*(1-dlz); grid(INV)=grid(INV)+mscalar.*dw; weight(INV)=weight(INV)+dw;
% NE
dw=dlx.*(1-dlz); grid(INE)=grid(INE)+mscalar.*dw; weight(INE)=weight(INE)+dw;
% SV
dw=(1-dlx).*dlz; grid(ISV)=grid(ISV)+mscalar.*dw; weight(ISV)=weight(ISV)+dw;
% SE
dw=dlx.*dlz; grid(ISE)=grid(ISE)+mscalar.*dw; weight(ISE)=weight(ISE)+dw;

Inoweight=find(weight==0);
if length(Inoweight)>0 display('warning: lack of markers in a cell'); end
grid=grid./weight;
grid(Inoweight)=nan;


dxnew=(max(x)-min(x))/(Snew-1); dznew=(max(z)-min(z))/(Tnew-1);
xnew=min(x):dxnew:max(x); znew=min(z):dznew:max(z);
[X,Z] = meshgrid(x,z); [Xnew,Znew] = meshgrid(xnew,znew);
interpgrid=interp2(X,Z,grid',Xnew,Znew,'bilin')';
weight=zeros(Snew,Tnew);
grid=zeros(Snew,Tnew);

s=floor(mx./dxnew); t=floor(mz./dznew);
%due to regridding, some markers may have been left outside of the grid.
%when gridding here, they are assumed to be in their nearest cell
outsiders=find(s<0); s(outsiders)=0; outsiders=find(s>Snew-2); s(outsiders)=Snew-2;
outsiders=find(t<0); t(outsiders)=0; outsiders=find(t>Tnew-2); t(outsiders)=Tnew-2;
INV=t*Snew+s+1;
INE=t*Snew+s+2;
ISV=(t+1)*Snew+s+1;
ISE=(t+1)*Snew+s+2;
s=s+1; t=t+1;
dlx=(mx-xnew(s))/dxnew;
dlz=(mz-znew(t))/dznew;
% NV
dw=(1-dlx).*(1-dlz); grid(INV)=grid(INV)+mscalar.*dw; weight(INV)=weight(INV)+dw;
% NE
dw=dlx.*(1-dlz); grid(INE)=grid(INE)+mscalar.*dw; weight(INE)=weight(INE)+dw;
% SV
dw=(1-dlx).*dlz; grid(ISV)=grid(ISV)+mscalar.*dw; weight(ISV)=weight(ISV)+dw;
% SE
dw=dlx.*dlz; grid(ISE)=grid(ISE)+mscalar.*dw; weight(ISE)=weight(ISE)+dw;


Iposweight=find(weight>0); Inoweight=find(weight==0);
grid(Iposweight)=grid(Iposweight)./weight(Iposweight);
grid(Inoweight)=interpgrid(Inoweight);

grid=grid';
%plot3(mx,mz,mscalar,'r.'); hold on; plot3(Xnew(:),Znew(:),grid(:),'g.');
% pcolor(Xnew,Znew,grid); shading flat;
end